import {
  Children,
  cloneElement,
  createElement,
  HTMLAttributes,
  isValidElement,
  ReactNode,
  useState,
  type FC,
} from 'react';
import classNames from 'classnames';
import { dropdownItemDefaultProps } from './defaultProps';
import type { DropdownItemOptions } from './type';
import DropdownMenu from './DropdownMenu';
import { useDropdownContext } from './DropdownContext';

export interface DropdownItemProps extends DropdownItemOptions, Omit<HTMLAttributes<HTMLDivElement>, 'onClick'> {}

const DropdownItem: FC<DropdownItemProps> = (props) => {
  const { className, ui, text, description, icon, value, children, forwardedRef, onClick, ...dropdownItemProps } =
    props;
  const [opened, setOpened] = useState(false);
  const [states, setStates] = useDropdownContext();

  let node: ReactNode;
  let handleClick: (e: MouseEvent) => void;

  if (children && Children.count(children) === 1 && isValidElement(children) && children.type === DropdownMenu) {
    node = cloneElement(children, { key: children.key ?? 'dropdownMenu', ...children.props, open: opened });
    handleClick = (e) => {
      onClick?.(value, e);
    };
  } else {
    node = children;
    handleClick = (e) => {
      setStates({ ...states, opened: false, value, text: text ?? node });
      onClick?.(value, e);
    };
  }

  return createElement(
    'div',
    {
      ref: forwardedRef,
      className: classNames({ ui }, 'item', className),
      onMouseEnter: () => setOpened(true),
      onMouseLeave: () => setOpened(false),
      onClick: handleClick,
      ...dropdownItemProps,
    },
    [
      icon && <i key="icon" className={classNames(icon, 'icon')}></i>,
      text && (
        <span key="text" className="text">
          {text}
        </span>
      ),
      description && (
        <span key="description" className="description">
          {description}
        </span>
      ),
      node,
    ],
  );
};

DropdownItem.displayName = 'DropdownItem';
DropdownItem.defaultProps = dropdownItemDefaultProps;

export default DropdownItem;
